#!/usr/bin/env python
import sys, os 
import logging
import sqlite3
from optparse import OptionParser

"""
Simple cross platform file sharing application.

Uses Zeroconf for discovery, http for transport, and comes with a variety of 
GUI implementations.

@author: Henry Finucane
@organization: TC Productions
@copyright: Copyright  2008 Henry Finucane
@contact: h.finucane NOSPAM_AT GMAIL [dot] com
"""

if sys.platform == 'win32':
    try:
        from wx_gui import gui
    except ImportError, e:
        import tk_gui as gui
    except Exception, e:
        print "Couldn't start GUI"
        print e
        exit(-1)

else:
    try:
        from gtk_gui import gui
    except ImportError, e:
        print e
        import tk_gui as gui
    except Exception, e:
        print "Couldn't start GUI"
        print e
        exit(-1)

try:
    import cherrypy_server
except ImportError, e:
    print "Need CherryPy: ", e
    exit(-1)
except Exception, e:
    print "Couldn't import CherryPy, something seems broken."
    print e
    exit(-1)

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-p", "--port", dest="PORT",
        help="server port", default=6899)
    parser.add_option("-c", "--configdir", dest="CONFIGDIR",
        help="Configuration file directory", 
        default=os.path.expanduser(r"~/.config/"))
    parser.add_option("-D", "--dbname", dest="DBNAME",
        help="Database file name", default="files.db")
    parser.add_option("-d", "--destination", dest="DOWNLOADTO",
        help="Download to this directory", 
        default=os.path.expanduser("~/Desktop/"))
    parser.add_option("-v", "--debug", "--verbose", dest="DEBUG",
        help="Be noisy about what's going on", action="store_true",
        default=False)
    parser.add_option("--wxpython", dest="USEWX",
        help="Use wxPython UI", action="store_true", 
        default=False)

    (env, args) = parser.parse_args()
    # Fake a dictionary:
    env.__getitem__ = lambda x: getattr(env,x)
    env.get = env.__getitem__
    env.__setitem__ = lambda y,z: setattr(env,y,z)

    env['CONFIGLOC'] = 'ffshare'
    env['DBTABLE'] = env['CONFIGLOC']+'_files'
    env['SELECT_ALL_PATHS'] = 'select path from ' + env['DBTABLE'] + ';'

    if env.get('DEBUG'):
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    if env.get('USEWX'):
        try:
            from wx_gui import gui
        except Exception, e:
            logging.critical("Cannot import wxPython layer because:\n%s" % e)

    # If configuration directory isn't there, create it
    if not os.path.isdir(env['CONFIGDIR']):
        os.mkdir(env['CONFIGDIR'])
    if not os.path.isdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) ):
        os.mkdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) )

    # If database is empty, create the schema
    conn = sqlite3.connect(os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME')))
    cursor = conn.cursor()
    if not cursor.execute('SELECT * FROM sqlite_master').fetchall():
        cursor.execute("""CREATE TABLE %s ( 
            path TEXT , 
            dir BOOL , 
            descend BOOL ) ; """ % (env['DBTABLE']))
        conn.commit()

    pid = os.fork()
    if pid == 0 :
        gui.Run(pid,env)
    else:
        cherrypy_server.server(env)
